package com.lo23.data.utils;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.xml.bind.JAXBElement;

public class DataUtils {

	/*
	 * Convert a jaxb list to a specified object list
	 * 
	 * @param xmlListObject The jaxb list to convert @param objectClass The
	 * object class to convert to @param xmlObjectClass The xmlObject contained
	 * in the jaxb list
	 */
	@SuppressWarnings("unchecked")
	public static ArrayList fromXMLListToObjectList(
			List<JAXBElement<Object>> xmlListObject, Class objectClass,
			Class xmlObjectClass) {

		ArrayList listObject = new ArrayList();
		Class[] classParm = { xmlObjectClass };
		try {
			for (JAXBElement<Object> anItem : xmlListObject) {

				Object[] objectParm = { anItem.getValue() };
				// Get constructor that fit the needs
				java.lang.reflect.Constructor co = objectClass
						.getConstructor(classParm);
				// GInstantiate the object calling the constructor with
				// parameters
				listObject.add(co.newInstance(objectParm));

			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return listObject;
	}

	/*
	 * Convert a jaxb list to a specified object list
	 * 
	 * @param imgPath The image path @param destPath The destination path where
	 * to copy the image
	 */
	public static void copyImageToPath(String imgPath, String destPath,
			String imageFormat) {
		try {
			if (!(new File(imgPath).exists())) {
				throw new Exception("Image doesn't exist at " + imgPath);
			}
			ImageIcon imgico = new ImageIcon(imgPath);
			BufferedImage bimg = new BufferedImage(imgico.getIconWidth(),
					imgico.getIconHeight(), BufferedImage.TYPE_INT_RGB);

			Graphics2D g2 = bimg.createGraphics();
			g2.drawImage(imgico.getImage(), 0, 0, null);
			g2.dispose();

			ImageIO.write(bimg, imageFormat, new File(destPath));
		} catch (Exception e) {
			System.err.println(e);
		}

	}
	
	public static String nullString(String str){
		if (str == null){
			return "";
		}else{
			return str;
		}
	}

}
